package uk.ac.glasgow.demosocs.users;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;


/**
 * electorate is a collection of voter in one particular election
 * @author Administrator
 *
 */
public class Electorate implements UserStore, Serializable {

	private Map<String, Voter> mElectorateMap;
	
	private String mElectorateID;

	public Electorate(String id) {
		mElectorateID = id;
		mElectorateMap = new HashMap<String, Voter>();
	}

	/**
	 * get a collection of voters
	 * @return voter collection
	 */
	public Collection<Voter> getVoterCollection(){
		
		return mElectorateMap.values();
	}
	
	public String getElectorateID(){
		return mElectorateID;
	}
	
	public void setElectorateID(String id){
		mElectorateID = id;
	}
	
	/**
	 * get the voter by id
	 * @param voterID - string  guid
	 * @return voter object if found, null if not found
	 */
	public Voter getVoterByID(String voterID){
		Voter voter = mElectorateMap.get(voterID);
		
		//if there is no such voter return null;
		return voter;
	}
	
	/**
	 * test if the eletorate contains the guid
	 * @param guid
	 * @return boolean
	 */
	public boolean containsGUID(String guid){
		return mElectorateMap.containsKey(guid);
	}
	

	@Override
	public void addUser(String surname, String GUID, String forename,
			String password) {
		Voter voter = new Voter(surname,forename,GUID,password);
		mElectorateMap.put(GUID, voter);
	}
	
	/**
	 * add an existing voter to the collection
	 * @param voter Voter object
	 */
	public void addAnExistingVoter(Voter voter){
		mElectorateMap.put(voter.getUserGUID(), voter);
	}

	@Override
	/**
	 * get the user based on guid and password,
	 * return null if not valied
	 */
	public User getUser(String GUID, String password) {
		User user = getVoterByID(GUID);
		if(user.authenticate(password))
			return user;
		else
			return null;
	}
	
	/**
	 * test if the password matches the guid
	 * @param guid
	 * @param password
	 * @return
	 */
	public boolean matche(String guid, String password){
		if(this.containsGUID(guid)){
			Voter voter = getVoterByID(guid);
			return voter.authenticate(password);
		} else 
			return false;
	}
	
}
